package cn.scau.server.config;

import cn.scau.server.utils.LoginInterceptor;
import cn.scau.server.utils.RedisTokenInterceptor;
import cn.scau.server.utils.StringToDateConvter;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;


@Configuration
public class WebConfig implements WebMvcConfigurer {
    /**
     * 配置日期类型转换组件
     * @param registry
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new StringToDateConvter());
    }

    /**
     * 拦截器
     * */
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 请求拦截器（Token 验证）
        registry.addInterceptor(new RedisTokenInterceptor(stringRedisTemplate))
                .addPathPatterns("/**")
                .order(0);

        // 登录拦截器（进一步检查用户是否登录）
        registry.addInterceptor(new LoginInterceptor())
                .excludePathPatterns("/mobileUser/login")
                .excludePathPatterns("/pcUser/login")
                .order(1);
    }

    /**
     * 跨域请求
     * */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:8888", "http://localhost:8889")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true);
    }
}
